using System.Transactions;
using CoreManager.API.Common;
using CoreManager.Models.DTOs;
using CoreManager.Services.Menus;
using Microsoft.AspNetCore.Mvc;

namespace CoreManager.API.System.Controllers
{
    /// <summary>
    /// 菜单管理控制器   
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class MenuController : BaseController
    {
        private readonly IMenuService _menuService;
        private readonly ILogger<MenuController> _logger;

        public MenuController(IMenuService menuService, ILogger<MenuController> logger) : base(logger)
        {
            _menuService = menuService;
            _logger = logger;
        }

        /// <summary>
        /// 根据Key更新菜单
        /// </summary>
        /// <param name="key">菜单Key</param>
        /// <param name="updateDto">更新菜单DTO</param>
        /// <returns></returns>
        [HttpPut("key/{key}")]
        public async Task<IActionResult> UpdateMenuByKey(string key, [FromBody] UpdateMenuDto updateDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("请求参数无效");
            }

            var result = await _menuService.UpdateMenuByKeyAsync(key, updateDto);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet("tree")]
        public async Task<IActionResult> GetMenuTree()
        {
            _logger.LogInformation("current user: {UserName}", GetCurrentUserName()); var result = await _menuService.GetMenuTreeAsync();
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 获取用户菜单
        /// </summary>
        /// <param name="userId">用户ID，如果不传则使用当前登录用户</param>
        /// <returns></returns>
        [HttpGet("user-menus")]
        public async Task<IActionResult> GetUserMenus([FromQuery] int? userId = null)
        {
            // 如果没有传用户ID，使用当前登录用户ID
            var currentUserId = userId ?? GetCurrentUserId();
            var result = await _menuService.GetUserMenusAsync(currentUserId);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 根据ID获取菜单详情
        /// </summary>
        /// <param name="id">菜单ID</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetMenuById(int id)
        {
            var result = await _menuService.GetMenuByIdAsync(id);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 根据查询条件获取菜单列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetMenus([FromQuery] MenuQueryDto query)
        {
            var result = await _menuService.GetMenusAsync(query);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 创建菜单
        /// </summary>
        /// <param name="createDto">创建菜单DTO</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateMenu([FromBody] CreateMenuDto createDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("请求参数无效");
            }
            var result = await _menuService.CreateMenuAsync(createDto);
            return result.Code == 200 ? Success(result.Data!, result.Message) : Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 更新菜单
        /// </summary>
        /// <param name="id">菜单ID</param>
        /// <param name="updateDto">更新菜单DTO</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateMenu(int id, [FromBody] UpdateMenuDto updateDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("请求参数无效");
            }

            var result = await _menuService.UpdateMenuAsync(id, updateDto);
            return result.Code == 200 ? Success(result.Data!, result.Message) : Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="id">菜单ID</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteMenu(int id)
        {
            var result = await _menuService.DeleteMenuAsync(id);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 批量删除菜单
        /// </summary>
        /// <param name="ids">菜单ID列表</param>
        /// <returns></returns>
        [HttpDelete("batch")]
        public async Task<IActionResult> BatchDeleteMenus([FromBody] List<int> ids)
        {
            if (ids == null || !ids.Any())
            {
                return BadRequest("请选择要删除的菜单");
            }

            var result = await _menuService.BatchDeleteMenusAsync(ids);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 更新菜单状�?        /// </summary>
        /// <param name="id">菜单ID</param>
        /// <param name="status">状态/param>
        /// <returns></returns>
        [HttpPatch("{id}/status")]
        public async Task<IActionResult> UpdateMenuStatus(int id, [FromBody] int status)
        {
            if (status < 0 || status > 1)
            {
                return BadRequest("状态值无效");
            }

            var result = await _menuService.UpdateMenuStatusAsync(id, status);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 批量更新菜单状态       
        /// </summary>
        /// <param name="request">批量更新请求</param>
        /// <returns></returns>
        [HttpPatch("batch/status")]
        public async Task<IActionResult> BatchUpdateMenuStatus([FromBody] BatchUpdateStatusRequest request)
        {
            if (request.Ids == null || !request.Ids.Any())
            {
                return BadRequest("请选择要更新的菜单");
            }

            if (request.Status < 0 || request.Status > 1)
            {
                return BadRequest("状态值无效");
            }

            var result = await _menuService.BatchUpdateMenuStatusAsync(request.Ids, request.Status);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 获取父级菜单选项
        /// </summary>
        /// <returns></returns>
        [HttpGet("parent-options")]
        public async Task<IActionResult> GetParentMenuOptions()
        {
            var result = await _menuService.GetParentMenuOptionsAsync();
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }

        /// <summary>
        /// 检查菜单Key是否存在
        /// </summary>
        /// <param name="key">菜单Key</param>
        /// <param name="excludeId">排除的菜单ID</param>
        /// <returns></returns>
        [HttpGet("check-key")]
        public async Task<IActionResult> CheckMenuKeyExists([FromQuery] string key, [FromQuery] int? excludeId = null)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return BadRequest("菜单Key不能为空");
            }

            var result = await _menuService.CheckMenuKeyExistsAsync(key, excludeId);
            if (result.Code == 200)
            {
                return Success(result.Data!, result.Message);
            }
            return Fail(result.Message, result.Code);
        }
    }

    /// <summary>
    /// 批量更新状态   
    /// </summary>
    public class BatchUpdateStatusRequest
    {
        /// <summary>
        /// 菜单ID列表
        /// </summary>
        public List<int> Ids { get; set; } = [];

        /// <summary>
        ///  状态     
        /// </summary>
        public int Status { get; set; }
    }
}